  <template>
  <div
    class="wrapper"
    v-loading="loading"
    element-loading-text="配置初始化中..."
    element-loading-svg-view-box="-10, -10, 50, 50"
    element-loading-background="rgba(122, 122, 122, 0.8)"
  >
    <div class="content">
      <!--画面div-->
      <div class="main-window" id="large"></div>
      <!-- <div class="sub-window-wrapper"> -->
      <!--小画面div-->
      <!-- <template v-if="remoteStreams.length">
          <div
            v-for="item in remoteStreams"
            :key="item.getId()"
            class="sub-window"
            ref="small"
            :data-uid="item.getId()"
          ></div>
        </template>
        <div v-else class="sub-window" ref="small">
          <span class="loading-text">等待对方加入…</span>
        </div> -->
      <!-- </div> -->
      <div class="chat">
        <chatPanelVue></chatPanelVue>
      </div>
    </div>
    <!--底层栏-->
    <ul class="tab-bar">
      <li class="set-wrapper" @click="toggleShareScreen">
        <a href="javascript:;" class="set">{{
          isSharing ? "停止共享" : "开始共享"
        }}</a>
      </li>
      <el-button type="danger" round size="default" @click="handleStopLive"
        >结束直播</el-button
      >
      <el-button type="success" round size="default" @click="handleOpen"
        >上架商品</el-button
      >
    </ul>
  </div>
  <getGoodsVue ref="GoodsDialog"></getGoodsVue>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { onMounted, onUnmounted, ref } from "vue-demi";
import { useRoute, useRouter } from "vue-router";
import { getUserToken } from "../../api/teacher";
import config from "../../config";
import storage from "../../utils/storage";
import chatPanelVue from "./chatPanel.vue";
import getGoodsVue from "./getGoods.vue";

const loading = ref(true);

const route = useRoute();
const router = useRouter()
const isSharing = ref(false);
const client = ref(null);
const localUid = Math.ceil(Math.random() * 1e5);
const localStream = ref(null);
const remoteStreams = ref([]);
const max = ref(4);

onMounted(() => {
  // 初始化音视频实例
  console.info("初始化音视频sdk");
  window.self = this;

  client.value = WebRTC2.createClient({
    appkey: config.appkey,
    debug: !true,
  });

  // 获取token
  initGetUserToken();
});

const initGetUserToken = async () => {
  const res = await getUserToken({
    userId: storage.getStorage("teacher_user").userId,
    uid: localUid,
    appkey: config.appkey,
    appSecret: config.appSecret,
    channelName: route.query.channelName,
  });
  console.log(res);
  if (res && typeof res == "object") {
    // 加入频道
    joinChannel(res.token);
  }
};

const joinChannel = (token) => {
  if (!client.value) {
    ElMessage({
      message: "内部错误，请重新加入房间",
      type: "error",
    });
    return;
  }
  console.info("开始加入房间: ", route.query.channelName);

  client.value
    .join({
      channelName: route.query.channelName,
      uid: localUid,
      token,
    })
    .then((data) => {
      console.info("加入房间成功，开始初始化本地音视频流");
      initLocalStream(); //初始化本地流
    })
    .catch((error) => {
      console.error("加入房间失败：", error);
      ElMessage({
        message: `${error}: 请检查appkey或者token是否正确`,
        type: "error",
      });
      // this.returnJoin();
    });
};

const initLocalStream = () => {
  //初始化本地的Stream实例，用于管理本端的音视频流
  localStream.value = WebRTC2.createStream({
    uid: localUid,
    audio: true, //是否启动mic
    video: false, //是否启动camera
    screen: false, //是否启动屏幕共享
  });

  //设置本地视频质量
  localStream.value.setVideoProfile({
    resolution: WebRTC2.VIDEO_QUALITY_720p, //设置视频分辨率
    frameRate: WebRTC2.CHAT_VIDEO_FRAME_RATE_20, //设置视频帧率
  });

  //设置本地音频质量
  localStream.value.setAudioProfile("music_standard");

  localStream.value
    .init()
    .then(() => {
      console.warn("音视频开启完成，可以播放了");
      // const div = self.$refs.large;
      const div = document.getElementById("large");
      localStream.value.play(div);
      localStream.value.setLocalRenderMode({
        // 设置视频窗口大小
        width: div.clientWidth,
        height: div.clientHeight,
        cut: true, // 是否裁剪
      });
      // 发布
      publish();
    })
    .catch((err) => {
      console.warn("音视频初始化失败: ", err);
      ElMessage({
        message: `音视频初始化失败`,
        type: "error",
      });
      localStream.value = null;
    });
};

const publish = () => {
  console.info("开始发布视频流");
  //发布本地媒体给房间对端
  client.value
    .publish(localStream.value)
    .then(() => {
      loading.value = false
      console.warn("本地 publish 成功");
      // handleAddPushWork(); //添加推流任务
    })
    .catch((err) => {
      console.error("本地 publish 失败: ", err);
      ElMessage({
        message: `本地 publish 失败`,
        type: "error",
      });
    });
};

//
const pushTaskID = ref(""); //推流任务id
const handleAddPushWork = () => {
  // 互动直播的推流任务，可以设置多个推流任务
  let rtmpTasks = [];
  let taskId = `taskId_${localUid}`;
  pushTaskID.value = taskId;
  let streamUrl =
    "rtmp://p66f02e88.live.126.net/live/89605cd0e7654212be6e272c9f901579?wsSecret=c07d1d2e1377c02835bacf573d99c9a0&wsTime=1658383886";
  // 设置是否进行互动直播录制，请注意与音视频通话录制区分。
  let record = true;
  let task1 = {
    taskId,
    streamUrl,
    record,
    // 整体布局参数
    layout: {
      canvas: {
        //整体布局宽度
        width: 1280,
        //整体布局高度
        height: 720,
        //整体布局背景色（转为10进制的数，如：#FFFFFF 16进制转为10进制为 16777215）
        color: 16777215,
      },
      users: [
        {
          uid: localUid, //用户id
          x: 0, // user1 的视频布局x偏移，相对整体布局的左上角（前提是推流发布user1的视频）
          y: 0, // user1 的视频布局y偏移，相对整体布局的左上角（前提是推流发布user1的视频）
          width: 10, // user1 的视频布局宽度（前提是推流发布user1的视频）
          height: 10, //user1 的视频布局高度（前提是推流发布user1的视频）
          adaption: 1, //自适应，值默认为1
          pushAudio: true, // 推流是否发布user1 的音频
          pushVideo: true, // 推流是否发布user1的视频
        },
      ],
      images: [
        {
          url: "xxxxxx", //设置背景图片
          x: 0, // 背景图片x偏移，相对整体布局的左上角
          y: 0, // 背景图片y偏移，相对整体布局的左上角
          width: 480, // 背景图片宽度
          height: 360, //背景图片高度
          adaption: 1, //自适应，值默认为1
        },
      ],
    },
  };
  rtmpTasks.push(task1);
  client.value
    .addTasks({ rtmpTasks })
    .then(() => {
      console.log("添加推流任务接口成功");
    })
    .catch((error) => {
      console.warn("添加推流任务接口失败: ", error);
      if (error == "INVALID_PARAMETER") {
        console.log("参数错误");
      }
    });
};

const toggleShareScreen = () => {
  if (!localStream.value) {
    throw Error("内部错误，请重新加入房间");
  }
  if (isSharing.value) {
    closeShare();
  } else {
    openShare();
  }
};

const openShare = () => {
  return localStream.value
    .open({
      type: "screen",
      screenAudio: true,
    })
    .then(
      () => {
        const div = document.getElementById("large");
        localStream.value.play(div);
        localStream.value.setLocalRenderMode({
          // 设置视频窗口大小
          width: div.clientWidth,
          height: div.clientHeight,
          cut: true, // 是否裁剪
        });
        isSharing.value = true;
        console.warn("打开屏幕共享成功");
        handleAddPushWork(); //添加推流任务
      },
      (err) => {
        console.error("打开屏幕共享失败: ", err);
      }
    );
};

const closeShare = () => {
  return localStream.value
    .close({
      type: "screen",
    })
    .then(
      () => {
        isSharing.value = false;
        console.warn("关闭屏幕共享 success");
      },
      (err) => {
        console.error("关闭屏幕共享 error: ", err);
      }
    );
};

// 结束直播
const handleStopLive = () => {
  if (isSharing.value) {
    ElMessage({
      type: "warning",
      message: "请先停止共享",
    });
    return false;
  }
  // 删除推流任务
  let taskIds = [];
  taskIds.push(pushTaskID.value);
  client.value
    .deleteTasks({
      taskIds,
    })
    .then(() => {
      console.log("删除推流任务接口调用成功");
      ElMessage({
        type: "success",
        message: "删除推流任务接口调用成功",
      });
      window.localStorage.clear()
      router.push('/login')
    })
    .catch((error) => {
      console.warn("删除推流任务接口调用失败: ", error);
      ElMessage({
        type: "error",
        message: "删除推流任务接口调用失败",
      });
      if (error == "INVALID_PARAMETER") {
        console.log("参数错误");
      }
    });
};

onUnmounted(() => {
  handleStopLive();
});

// 上架商品
const GoodsDialog = ref();
const handleOpen = () => {
  GoodsDialog.value.initData();
  GoodsDialog.value.initAdded();
  GoodsDialog.value.show = true;
};
</script>



<style scoped lang='scss'>
.wrapper {
  height: 100vh;
  background-image: linear-gradient(179deg, #141417 0%, #181824 100%);
  display: flex;
  flex-direction: column;
  .content {
    flex: 1;
    display: flex;
    position: relative;
    .main-window {
      border: 1px solid #ffffff;
      height: 100%;
      // width: 180vh;
      position: absolute;
      width: 79.5%;
      background: #25252d;
      ::v-deep(.nertc-screen-container) {
        width: 100% !important;
      }
    }

    .sub-window-wrapper {
      position: absolute;
      top: 16px;
      right: 16px;
      z-index: 9;
      width: 165px;
    }

    // .sub-window {
    //   background: #25252d;
    //   border: 1px solid #ffffff;
    //   margin-bottom: 20px;

    //   .loading-text {
    //     display: block;
    //     width: 100%;
    //     text-align: center;
    //     line-height: 90px;
    //     font-size: 12px;
    //     color: #fff;
    //     font-weight: 400;
    //   }
    // }
    .chat {
      border: 1px solid #fffefe;
      position: absolute;
      top: 0;
      right: 0;
      bottom: -2px;
      overflow: hidden;
      z-index: 9;
      width: 20%;
      background: #000000;
    }
  }

  .tab-bar {
    height: 54px;
    background-image: linear-gradient(180deg, #292933 7%, #212129 100%);
    box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.3);
    list-style: none;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
    li {
      height: 54px;
      width: 125px;
      cursor: pointer;

      &.set-wrapper {
        display: flex;
        justify-content: center;
        align-items: center;

        &:hover {
          background-color: #18181d;
        }

        .set {
          background-color: #2a6af2;
          color: #fff;
          display: inline-block;
          width: 68px;
          height: 36px;
          text-align: center;
          line-height: 36px;
          font-size: 12px;
          text-decoration: none;
          font-weight: 500;
          border-radius: 100px;
        }
      }

      //结束按钮
      &.over {
        background: url("../../assets/img/icon/over.png") no-repeat center;
        background-size: 68px 36px;

        &:hover {
          background: url("../../assets/img/icon/over-hover.png") no-repeat
            center;
          background-size: 68px 36px;
        }

        &:active {
          background: url("../../assets/img/icon/over-click.png") no-repeat
            center;
          background-size: 68px 36px;
        }
      }
    }
  }
}
</style>